class_name Ship_01
extends BaseShip

@onready var shoot_point: Marker2D = $ShootPoint
@onready var shot_wait_timer: Timer = $Timer/ShotWaitTimer
@onready var transmit_wait_timer: Timer = $Timer/TransmitWaitTimer
@onready var invincible_timer: Timer = $Timer/InvincibleTimer
@onready var ammo_scene = preload("res://scenes/ammo/laser.tscn")
@onready var status_ui: Control = $StatusUI

var can_shot: bool = true
var pending_damage

var transmit_direction: Vector2

var transmit_wait_time:
	set(v):
		transmit_wait_timer.wait_time = v

var shot_wait_time:
	set(v):
		shot_wait_timer.wait_time = v

func _ready() -> void:
	Game.initialize_stats(self)
	animation_player.play("running")
	transmit_wait_time = stats.transmit_wait_time
	shot_wait_time = stats.shot_wait_time
	await get_parent().ready
	shot()
	shot_wait_timer.start()

#func _unhandled_input(event: InputEvent) -> void:
	#if event.is_action_pressed("transmit"):
		#transmit_request_timer.start()

func _physics_process(_delta: float) -> void:
	Game.travel_mileage += 1
	if can_shot:
		shot()
		shot_wait_timer.start()
	if pending_damage:
		state_machine.change_state("Hurt")

func shot() -> void:
	var ammo_number = Game.game_stats.ammo_number
	#Game.instance_ammo(ammo_scene, shoot_point.global_position, Game.ammo, shoot_point.global_rotation, self)
	#for angle in [-0.4, -0.2, 0, 0.2, 0.4]:
		#Game.instance_ammo(ammo_scene, shoot_point.global_position, Game.ammo, shoot_point.global_rotation + angle)
	for angle in ammo_number:
		Game.instance_ammo(ammo_scene, shoot_point.global_position, Game.ammo, shoot_point.global_rotation + (-0.1) * (ammo_number - 1) + 0.2 * angle, self)
	
	can_shot = false

func should_transmit() -> bool:
	if Input.is_action_just_pressed("transmit") and transmit_wait_timer.is_stopped() and (stats.energy >= stats.transmit_cost):
		return true
	return false

func is_collide_border() -> bool:
	#检测是否碰撞到边界
	return is_on_ceiling() or is_on_floor() or is_on_wall()

func _on_shot_wait_timer_timeout() -> void:
	can_shot = true

func _on_hurtbox_hurt(hitbox: Hitbox) -> void:
	if invincible_timer.time_left > 0:
		return
	
	pending_damage = Damage.new()
	pending_damage.amount = Game.calculate_damage(hitbox.owner, self)
	pending_damage.source = hitbox.owner
